﻿/******
Custom validation message displayer by Torben Rohde (trsdomain.dk)
*******/
var validationDisplayer = (function()
{
	var currentlyShownValErrors = {};

	var hideAllValidationErrors = function hideAllValidationErrors()
	{
		for (var valErrShown in currentlyShownValErrors)
		{
			if (currentlyShownValErrors.hasOwnProperty(valErrShown))
			{
				if (currentlyShownValErrors[valErrShown])
				{
					$("#val_" + valErrShown).hide();
					$("#" + valErrShown).removeClass("invalid");
					currentlyShownValErrors[valErrShown] = false;
				}
			}
		}
	}
	var showValidationError = function showValidationError(text, elem, position)
	{
		if (!position)
		{
			position = "rightof_middle";
		}
		if (currentlyShownValErrors[elem.attr("id")])
		{
			return;
		}
		//create DOM element if non-existent
		var valID = "val_" + elem.attr("id");
		var valElem = $("#" + valID);
		if (valElem.length === 0)
		{
			$(".main").append("<div id=\"" + valID + "\" class=\"invalidBox\">" + text + "</div>");
			valElem = $("#" + valID);
			positionValidation(position, valElem, elem);
			valElem.show();
		}
		else
		{
			valElem.show();
		}
		currentlyShownValErrors[elem.attr("id")] = { text: text, valElem: valElem, elem: elem, position: position };

		elem.addClass("invalid");
		elem.focus();
	}
	
	$(window).resize(function() {
		for (var valErrShown in currentlyShownValErrors)
		{
			if (currentlyShownValErrors.hasOwnProperty(valErrShown))
			{
				if (currentlyShownValErrors[valErrShown])
				{
					var valProps = currentlyShownValErrors[valErrShown];
					positionValidation(valProps.position, valProps.valElem, valProps.elem);
				}
			}
		}
	});

	var positionValidation = function positionValidation(position, valElem, elem)
	{
			var pos = elem.position();
			var left = 0;
			var top = 0;
			if (position === "rightof_middle")
			{
				left = pos.left + elem.outerWidth() + 10;
				top = pos.top - 1;
			}
			else if (position === "below_right")
			{
				top = pos.top + elem.outerHeight() + 3;
				left = pos.left + elem.outerWidth() - valElem.outerWidth();
			}
			valElem.css({ "top": top + "px", "left": left + "px" });
	}

	return {
		hideAllValidationErrors: hideAllValidationErrors,
		showValidationError: showValidationError,
	};
}); //end validationDisplayer